package com.bii.gelapp;

import java.io.ByteArrayOutputStream;
import java.io.File;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MarkerGaborActivity extends Activity {

	private static final int SELECT_PICTURE = 0;
	public static final int GALLERY_CHOOSER_INTENT = 1;

	public static String picturePath;
	public static String filetitle = "";
	Button btImage, btSegment, btFilter;
	ImageView ivImage;
	TextView tvThreshold;
	SeekBar sbThreshold;
	public Bitmap originalBmp; // origin
	public Bitmap activeBmp; // edited image
	Bitmap takenBmp;
	public static String filename;
	public static Bitmap colorBmp;

	/*
	 * int kernelSize = 24; double sigma = 8; double theta = Math.PI / 2; double
	 * lambda = 21; double gamma = 1; double psi = 1.5;
	 */

	int kernelSize = 24;
	double sigma = 30;
	double theta = Math.PI / 2;
	double lambda = 28;
	double gamma = 1;
	double psi = 1.5;

	int currentprogress;
	int thresholdvalue;

	public String filepath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.markergaboractivity);
		ivImage = (ImageView) findViewById(R.id.ivImage);

		tvThreshold = (TextView) findViewById(R.id.tvThreshold);

		btImage = (Button) findViewById(R.id.btImage);
		btImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, GALLERY_CHOOSER_INTENT);
			}
		});

		btSegment = (Button) findViewById(R.id.btSegment);
		btFilter = (Button) findViewById(R.id.btFilter);
		btFilter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Mat filtermat = new Mat(originalBmp.getHeight(), originalBmp
						.getWidth(), CvType.CV_8U);
				Utils.bitmapToMat(originalBmp, filtermat);
				Imgproc.cvtColor(filtermat, filtermat, Imgproc.COLOR_BGR2GRAY);

				// result image below
				Mat resultImg = new Mat();
				// set gabor
				Mat gaborKernel = Imgproc.getGaborKernel(new Size(kernelSize,
						kernelSize), sigma, theta/* horizontal */, lambda,
						gamma, psi, CvType.CV_32F);

				Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

				Bitmap filteredBmp = Bitmap.createBitmap(resultImg.cols(),
						resultImg.rows(), Bitmap.Config.ARGB_8888);
				Utils.matToBitmap(resultImg, filteredBmp);

				activeBmp = filteredBmp;
				// display result
				ivImage.setImageBitmap(filteredBmp);
				// apply gabor before threshold
				sbThreshold.setEnabled(true);
				// btFilter.setEnabled(true);

				btSegment.setEnabled(true);
			}
		});
		// apply gabor before threshold
		sbThreshold = (SeekBar) findViewById(R.id.sbThreshold);
		sbThreshold.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (activeBmp == null) {
					if (takenBmp == null) {
						takenBmp = originalBmp;
					}
				} else {
					if (takenBmp == null) {
						takenBmp = activeBmp;
					}
				}

				currentprogress = sbThreshold.getProgress();
				thresholdvalue = currentprogress;
				if (currentprogress != 0) {
					Mat srcImg = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = takenBmp.copy(Bitmap.Config.ARGB_8888,
							true);
					Utils.bitmapToMat(myBitmap32, srcImg);
					Mat thresholdMat = new Mat();
					Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
							255, Imgproc.THRESH_BINARY);
					Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
							thresholdMat.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(thresholdMat, thBmp);

					ivImage.setImageBitmap(thBmp);
					tvThreshold.setText("Threshold: " + currentprogress);
					activeBmp = thBmp;
				} else {

					ivImage.setImageBitmap(takenBmp);
					tvThreshold.setText("Threshold: " + currentprogress);
				}

			}
		});

		// prevent clicking until file is selected
		btSegment.setEnabled(false);
		btSegment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(),
						MarkerSegmentationActivity.class);
				byte[] bytes;
				if (activeBmp == null) {
					bytes = compressImage(originalBmp);
				} else {
					bytes = compressImage(activeBmp);
				}
				goToNextActivity.putExtra("BMP", bytes);
				startActivity(goToNextActivity);

			}
		});

		btFilter.setEnabled(false);
		sbThreshold.setEnabled(false);
		btSegment.setEnabled(false);

		if (getIntent().hasExtra("imgsrc")) {
			picturePath = getIntent().getStringExtra("imgsrc");
			originalBmp = BitmapFactory.decodeFile(picturePath);
			colorBmp = BitmapFactory.decodeFile(picturePath);
			Mat srcImg = new Mat(originalBmp.getHeight(),
					originalBmp.getWidth(), CvType.CV_8U, new Scalar(4));
			Bitmap myBitmap32 = originalBmp.copy(Bitmap.Config.ARGB_8888, true);
			Utils.bitmapToMat(myBitmap32, srcImg);
			Mat grayImg = new Mat();
			Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
			originalBmp = Bitmap.createBitmap(grayImg.cols(), grayImg.rows(),
					Bitmap.Config.RGB_565);
			Utils.matToBitmap(grayImg, originalBmp);

			activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true);

			ivImage.setImageBitmap(originalBmp);
			filetitle = getIntent().getStringExtra("mstitle");

			btFilter.setEnabled(true);
			// sbThreshold.setEnabled(true);

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK
				&& null != data) {
			/*
			 * Uri selectedImage = data.getData(); String[] filePathColumn = {
			 * MediaStore.Images.Media.DATA };
			 * 
			 * Cursor cursor = getContentResolver().query(selectedImage,
			 * filePathColumn, null, null, null); cursor.moveToFirst();
			 * 
			 * int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			 * picturePath = cursor.getString(columnIndex); cursor.close();
			 * originalBmp = BitmapFactory.decodeFile(picturePath); colorBmp =
			 * BitmapFactory.decodeFile(picturePath); Mat srcImg = new
			 * Mat(originalBmp.getHeight(), originalBmp.getWidth(),
			 * CvType.CV_8U, new Scalar(4)); Bitmap myBitmap32 =
			 * originalBmp.copy(Bitmap.Config.ARGB_8888, true);
			 * Utils.bitmapToMat(myBitmap32, srcImg);
			 * 
			 * // convert to grayscale Mat grayImg = new Mat();
			 * Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
			 * originalBmp = Bitmap.createBitmap(grayImg.cols(), grayImg.rows(),
			 * Bitmap.Config.RGB_565);
			 * 
			 * // convert mat back to bitmap set originalBmp
			 * Utils.matToBitmap(grayImg, originalBmp); // set activeBmp
			 * activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true); //
			 * Bitmap resizedbmp = Bitmap.createScaledBitmap(activeBmp, 300, //
			 * 300, true); ivImage.setImageBitmap(originalBmp); // allow users
			 * to click buttons btSegment.setEnabled(true);
			 * btFilter.setEnabled(true); // threshold only after filtering //
			 * sbThreshold.setEnabled(true);
			 */
		}
		if (requestCode == GALLERY_CHOOSER_INTENT) {
			// Get the filepath and display on imageview.

			filepath = getGalleryImagePath(data);
			// Check if the specified image exists.
			ivImage.requestLayout();
			if (filepath != null) {
				if (!new File(filepath).exists()) {
					Toast.makeText(this, "Image does not exist.",
							Toast.LENGTH_SHORT).show();
				} else {
					Bitmap img = BitmapFactory.decodeFile(filepath);
					originalBmp = BitmapFactory.decodeFile(filepath);
					colorBmp = BitmapFactory.decodeFile(filepath);
					Mat srcImg = new Mat(originalBmp.getHeight(),
							originalBmp.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = originalBmp.copy(
							Bitmap.Config.ARGB_8888, true);
					Utils.bitmapToMat(myBitmap32, srcImg);

					// convert to grayscale
					Mat grayImg = new Mat();
					Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
					originalBmp = Bitmap.createBitmap(grayImg.cols(),
							grayImg.rows(), Bitmap.Config.RGB_565);

					// convert mat back to bitmap set originalBmp
					Utils.matToBitmap(grayImg, originalBmp);
					// set activeBmp
					activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true);
					// Bitmap resizedbmp = Bitmap.createScaledBitmap(activeBmp,
					// 300,
					// 300, true);
					ivImage.setImageBitmap(originalBmp);
					// allow users to click buttons
					btSegment.setEnabled(true);
					btFilter.setEnabled(true);

				}
			}
		}

	}

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;

	}

	public String getGalleryImagePath(Intent data) {
		try {
			Uri imgUri = data.getData();
			String filePath = "";
			if (data.getType() == null) {
				// For getting images from default gallery app.
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(imgUri,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				filePath = cursor.getString(columnIndex);
				cursor.close();
			} else if (data.getType().equals("image/jpeg")
					|| data.getType().equals("image/png")) {
				filePath = imgUri.getPath();
			}
			return filePath;
		} catch (Exception e) {
			return null;
		}

	}

}
